package com.yh.tags;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class DateTag extends TagSupport {

	private Date date;

	private String format = "yyyy-MM-dd";

	public void setDate(Date date) {
		this.date = date;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	/**
	 * 内容处理完成
	 */
	@Override
	public int doAfterBody() throws JspException {
		// TODO Auto-generated method stub
		return super.doAfterBody();
	}

	/**
	 * 标签结束
	 */
	@Override
	public int doEndTag() throws JspException {
		// TODO Auto-generated method stub
		return super.doEndTag();
	}

	/**
	 * 标签开始
	 */
	@Override
	public int doStartTag() throws JspException {
//		pageContext
		try {
			if (date == null) {
				return super.doStartTag();
			}
			Instant instant = date.toInstant();
			ZoneId zoneId = ZoneId.systemDefault();
			LocalDateTime d = LocalDateTime.ofInstant(instant, zoneId);

			DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
			String str = formatter.format(d);

			//通过内置对象pageContext对结果进行输出
			pageContext.getOut().print(str);
		} catch (IOException e) {
			throw new JspException("格式化输出日期错误", e);
		}

		return super.doStartTag();
	}

}
